package com.autumn.juc.lock;

import org.openjdk.jol.info.ClassLayout;

public class LockEscalationDemo {
    public static void main(String[] args) throws InterruptedException {
        System.out.println(ClassLayout.parseInstance(new Object()).toPrintable());
        //Hotspot虚拟机在启动后有个 4s 的延迟才会对每个新建的对象开启偏向锁模式
        Thread.sleep(4000);
        Object obj = new Object();
        //若对象调用了hashCode，不会开启偏向锁模式，
        //因为偏向锁的Mark Word没有地方存放hashCode，而无锁的Mark Word有专门存放hashCode的地方，
        //因此会撤销偏向锁变成无锁状态
        //obj.hashCode();
        //System.out.println(">>>>>>>>>>>>>>>>>>>>>>" + ClassLayout.parseInstance(obj).toPrintable());

        //Thread thread1 = new Thread(new Runnable() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(">>>>>>>>>>>>>>>>>>>>>>" + Thread.currentThread().getName() + "开始执行……"
                        + ClassLayout.parseInstance(obj).toPrintable());
                synchronized (obj) {
                    //obj.hashCode();//偏向锁变重量级锁
                    //obj.notify();//偏向锁变轻量级锁
                    //try {
                    //    obj.wait(100);//偏向锁变重量级锁
                    //} catch (InterruptedException e) {
                    //    e.printStackTrace();
                    //}
                    System.out.println(">>>>>>>>>>>>>>>>>>>>>>" + Thread.currentThread().getName() + "获得锁执行中……"
                            + ClassLayout.parseInstance(obj).toPrintable());
                }
                System.out.println(">>>>>>>>>>>>>>>>>>>>>>" + Thread.currentThread().getName() + "释放锁……"
                        + ClassLayout.parseInstance(obj).toPrintable());
            }
        }, "thread1").start();
        //thread1.start();

        // 控制线程竞争时机
        //Thread.sleep(1);

        //Thread thread2 = new Thread(new Runnable() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(">>>>>>>>>>>>>>>>>>>>>>" + Thread.currentThread().getName() + "开始执行……"
                        + ClassLayout.parseInstance(obj).toPrintable());
                synchronized (obj) {
                    System.out.println(">>>>>>>>>>>>>>>>>>>>>>" + Thread.currentThread().getName() + "获得锁执行中……"
                            + ClassLayout.parseInstance(obj).toPrintable());
                }
                System.out.println(">>>>>>>>>>>>>>>>>>>>>>" + Thread.currentThread().getName() + "释放锁……"
                        + ClassLayout.parseInstance(obj).toPrintable());
            }
        }, "thread2").start();
        //thread2.start();

        Thread.sleep(5000);
        System.out.println(ClassLayout.parseInstance(obj).toPrintable());
    }
}
